package app.sys.controller;


import com.alibaba.excel.util.DateUtils;
import app.sys.mapper.FileMapper;
import app.sys.model.RetCode;
import app.sys.data.comm.GlobalCommData;
import app.sys.data.entity.FileInfo;
import app.sys.data.form.BusFileForm;
import app.sys.model.ResponseObj;
import app.sys.service.BusFileService;
import app.sys.service.FileService;
import app.sys.utils.FileUtil;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;

import static com.alibaba.excel.util.DateUtils.DATE_FORMAT_10;
import static com.alibaba.excel.util.DateUtils.DATE_FORMAT_14;

/**
 * 文件管理controller
 */
@RestController
@RequestMapping("/file")
public class FileController extends BaseRestController<FileService, FileMapper,
        FileInfo, String> {

    @Value("${file.path}")
    private String filePath;

    @Autowired
    private BusFileService busFileService;

    /**
     * 上传
     *
     * @param files 文件列表
     */
    @PostMapping("/uploadFile")
    public ResponseObj uploadFile(@RequestParam List<MultipartFile> files) {
        // 获取原图片名称
        for (MultipartFile file : files) {
            if (file.isEmpty()) {
                continue; //
            }
            // 验证文件类型和大小
            if (!file.getContentType().startsWith("image/") || file.getSize() > 1024 * 1024 * 5) {
                return new ResponseObj<>(null, "类型错误或者文件超过5M", RetCode.FAIL);
            }

            try {
                String fileOldName = file.getOriginalFilename();
                Date date = new Date();
                String dateCurrNyStr = DateUtils.format(date, DATE_FORMAT_10);
                String dateStr = DateUtils.format(date, DATE_FORMAT_14);
                String suffix = fileOldName.substring(fileOldName.lastIndexOf("."));

                String fileName = dateStr + GlobalCommData.UNDERLINE + RandomUtils.nextInt() + suffix;
                String fileTargetPath = filePath + dateCurrNyStr + File.separator;
                File directory = new File(fileTargetPath);
                if (!directory.exists()) {
                    directory.mkdir();
                }
                File dest = new File(fileTargetPath + fileName);
                file.transferTo(dest);
                //入库
                FileInfo fileInfo = new FileInfo();
                fileInfo.setFileName(fileOldName).setFileType(suffix.substring(1)).setFileSize(String.valueOf(file.getSize())).setFilePath(dateCurrNyStr + fileName);
                this.mapper.insert(fileInfo);
            } catch (IOException e) {
                return new ResponseObj<>(null, "文件上传失败", RetCode.FAIL);
            }
        }
        return new ResponseObj<>(null, RetCode.SUCCESS);
    }

    /**
     * 查看
     *
     * @param
     * @return
     */
    @GetMapping("/showFile")
    public ResponseObj showFile(HttpServletResponse response) {

        String fileTargetPath = "D:\\pet\\file\\2025-07-25\\" + "20250725100219_1514563554.jpg";


        FileUtil.showFile(fileTargetPath, response);
        return new ResponseObj<>(fileTargetPath, RetCode.SUCCESS);
    }

    /**
     * 文件下载 isOnline默认为false
     */
    @GetMapping("/downloadFile")
    public void downloadFile(String fileName, HttpServletResponse response) throws IOException {
        String fileTargetPath = "D:\\pet\\file\\2025-07-25\\" + "20250725100219_1514563554.jpg";

        // 路径可以指定当前项目相对路径
        File file = new File(fileTargetPath);
        FileInputStream fileInputStream = null;
        ServletOutputStream outputStream = null;
        try {
            if (file.exists()) {
                fileInputStream = new FileInputStream(file);
                outputStream = response.getOutputStream();

                // 获取文件扩展名
                String extension = fileName.substring(fileName.lastIndexOf(".") + 1);

                // 根据文件扩展名设置Content-Type
                String contentType = FileUtil.getContentType(extension);
                response.setContentType(contentType);

                // 如果文件名为中文需要设置编码
                response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "utf8"));
                // 返回前端文件名需要添加
                response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");

                byte[] bytes = new byte[1024];
                int len;
                while ((len = fileInputStream.read(bytes)) != -1) {
                    outputStream.write(bytes, 0, len);
                }
            }
        } finally {
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }
    }


    /**
     * 绑定业务表
     *
     * @param form 文入参
     */
    @PostMapping("/updateBisFile")
    public ResponseObj updateBisFile(@RequestBody BusFileForm form) {
        this.busFileService.saveBusFile(form);
        return new ResponseObj<>(null, RetCode.SUCCESS);
    }

}
